<?php

namespace app\admin\controller\coursetable;

use app\common\controller\Backend;
use fast\Tree;
/**
 *
 *
 * @icon fa fa-file
 */
class Classroomeplan extends Backend
{

    /**
     * Classroomeplan模型对象
     */
    protected $model = null;
    protected $noNeedRight=["lists","status","index","edit"];
    protected $noNeedLogin=["lists","status","index","edit"];


    public function _initialize()
    {
        parent::_initialize();
        $this->shopid=false;
        $this->model = model('Classroomeplan');
        $this->modelValidate = true;
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model->alias("classroomeplan")
                ->join("eb_classes classes", "classroomeplan.classes_id=classes.id", "LEFT")
                ->join("fa_course_table coursetable", "classroomeplan.table_id=coursetable.id", "LEFT")
                ->join("fa_ocation ocation", "classroomeplan.ocation_id=ocation.id", "LEFT")
                ->field("classroomeplan.*,classes.name as classes_name,coursetable.name as table_name,ocation.name as ocation_name");
            if(isset($_REQUEST["search"])&&$_REQUEST["search"]!=""){
                $total = $total->where("classes.name", "like", $_REQUEST["search"]);
            }
            $total = $total->where("classroomeplan.status", "<>", -1);
            $total = $total
                ->count();

            $list = $this->model->alias("classroomeplan")
                ->join("eb_classes classes", "classroomeplan.classes_id=classes.id", "LEFT")
                ->join("fa_course_table coursetable", "classroomeplan.table_id=coursetable.id", "LEFT")
                ->join("fa_ocation ocation", "classroomeplan.ocation_id=ocation.id", "LEFT")
                ->field("classroomeplan.*,classes.name as classes_name,coursetable.name as table_name,ocation.name as ocation_name");
            if(isset($_REQUEST["search"])&&$_REQUEST["search"]!=""){
                $list = $list->where("classes.name", "like", $_REQUEST["search"]);
            }
            //if ($_SESSION['think']['admin']['group_id'] == 2) {
            //    $list = $list->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            //}纬武社区教学点党群服务中心 2025级银龄春季养生保健基础3班
            $list = $list->where("classroomeplan.status", "<>", -1)
                ->order('classroomeplan.weigh desc,classroomeplan.id desc')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            // 调试：记录SQL和结果
            // \think\Log::write('Classroomeplan SQL: ' . $this->model->getLastSql(), 'debug');
            $list = collection($list)->toArray();
            for($i=0;$i<count($list);$i++){
                $list[$i]['classes_id']=model("Classes")->getClasses_idTextAttr($list[$i]['classes_id'],$list[$i]);
                $list[$i]['table_id']=model("Coursetable")->getCoursetable_idTextAttr($list[$i]['table_id'],$list[$i]);
                $list[$i]['ocation_id']=model("Ocation")->getOcation_idTextAttr($list[$i]['ocation_id'],$list[$i]);

                // 处理周几字段 - 支持多种格式
                if(isset($list[$i]['week']) && $list[$i]['week'] !== '' && $list[$i]['week'] !== null){
                    $weekMap = ['1'=>'周一', '2'=>'周二', '3'=>'周三', '4'=>'周四', '5'=>'周五', '6'=>'周六', '7'=>'周日'];
                    // 如果已经是中文，直接显示
                    if(strpos($list[$i]['week'], '周') !== false){
                        // 已经是中文格式，不处理
                    } else {
                        // 数字格式，需要转换
                        $weeks = explode(',', $list[$i]['week']);
                        $weekNames = [];
                        foreach($weeks as $w){
                            $w = trim($w);
                            if(isset($weekMap[$w])){
                                $weekNames[] = $weekMap[$w];
                            }
                        }
                        if(!empty($weekNames)){
                            $list[$i]['week'] = join(',', $weekNames);
                        }
                    }
                }

                // 处理时段字段 - 支持多种格式（可能是时间段如"08:30-10:00"或数字）
                if(isset($list[$i]['daytime']) && $list[$i]['daytime'] !== '' && $list[$i]['daytime'] !== null){
                    // 如果包含冒号，说明是时间格式，直接显示
                    if(strpos($list[$i]['daytime'], ':') !== false){
                        // 已经是时间格式，不处理
                    } else {
                        // 数字格式，需要转换
                        $daytimeMap = ['1'=>'上午', '2'=>'中午', '3'=>'下午', '4'=>'晚上'];
                        $daytimes = explode(',', $list[$i]['daytime']);
                        $daytimeNames = [];
                        foreach($daytimes as $d){
                            $d = trim($d);
                            if(isset($daytimeMap[$d])){
                                $daytimeNames[] = $daytimeMap[$d];
                            }
                        }
                        if(!empty($daytimeNames)){
                            $list[$i]['daytime'] = join(',', $daytimeNames);
                        }
                    }
                }
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
//        $this->assignconfig("relType",$_REQUEST['relType']);
//        $this->assignconfig("relId",$_REQUEST['relId']);
        $this->assignconfig("admin",$_SESSION['think']['admin']);
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    if($params['classes_id']<0||preg_match("/_/",$params['classes_id'])){
                        $this->error("请选择班级");
                    }
                    if(!isset($params['daytime'])||trim($params['daytime'])==""){
                        $this->error("请选择时段");
                    }
                    //验证是否使用对了教室的类型
                    $r=model("Ocation")->where("id","in",$params["ocation_id"])->select();
                    $r2=model("Classplant")->where("classes_id","in",$params["classes_id"])->where("status",1)->select();
                    if(isset($r)){
                        $ocation_type=$r[0]["ocation_type"];
                        if(!in_array($ocation_type,explode(",",$r2[0]["ocation_type"]))){
                            $this->error("该教室类型与所选教室类型不一致");
                        }
                    }
                    //如果该班级已经有排课记录，则提示
//                    $r=model("Classroomeplan")->where("classes_id","=",$params['classes_id'])->where("status","<>",-1)->select();
//                    if(count($r)>0){
//                        $this->error("该班级已经有指定教室记录，请先删除");
//                    }
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        //$this->model->validate($validate);
                    }
                    $datatime=date("Y-m-d H:i:s");
                    $params['create_time']=$datatime;
                    $params['update_time']=$datatime;
                    $params['status']=1;
                    unset($params['delete_time']);
                    unset($params['id']);
                    $result = $this->model->insertUpdate($params, ["table_id","classes_id","ocation_id","week","daytime"]);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $_REQUEST['classesName']=preg_replace("/\(.*$/","",$_REQUEST['classesName']);
        $classes=model("Classes")->where("name","like","%".$_REQUEST['classesName']."%")->where("status",1)->find();
        $this->assignconfig("classesName",urldecode($_REQUEST['classesName']));
        $this->assign("classesId",$classes["id"]);
        $this->assignconfig("subject_lv",$classes["subject_lv"]);
        $this->assignconfig("admin",$_SESSION['think']['admin']);
        return $this->view->fetch('add');
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {

        if($this->request->param('planids')>0){
            $r=model("Classplant")->where("id","in",$this->request->param('planids'))->select();
            if(isset($r)){
                $classesname=preg_replace("/\(.*$/","",$_REQUEST['classesName']);
                $classes=model("Classes")->where("name","=",$classesname)->where("status",1)->find();
                if(!isset($classes)){
                    $this->error("班级不存在");
                }

                $r2=model("Classroomeplan")->where("classes_id","in",$classes["id"])->where("status",1)->select();
                if(!isset($r2)){
                    header("Location: /coursetable/classroomeplan/add?classesName=".urlencode($_REQUEST['classesName']));
                    exit;
                }
                if(empty($r2)){
                    header("Location: /coursetable/classroomeplan/add?classesName=".urlencode($_REQUEST['classesName']));
                    exit;
                }else{
                    $ids=$r2[0]["id"];
                }
            }else{
                header("Location: /coursetable/classroomeplan/add?classesName=".urlencode($_REQUEST['classesName']));
                exit;
            }
        }


        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        //$row->validate($validate);
                    }
                    if(!isset($params['daytime'])||trim($params['daytime'])==""){
                        $this->error("请选择时段");
                    }
                    //验证是否使用对了教室的类型
                    $r=model("Ocation")->where("id","in",$params["ocation_id"])->select();
                    $r2=model("Classplant")->where("classes_id","in",$params["classes_id"])->where("status",1)->select();
                    if(isset($r)){
                        $ocation_type=$r[0]["ocation_type"];
                        if(!in_array($ocation_type,explode(",",$r2[0]["ocation_type"]))){
                            $this->error("该教室类型与所选教室类型不一致");
                        }
                    }
                    $datatime=date("Y-m-d H:i:s");
                    $params['update_time']=$datatime;
                    unset($params['delete_time']);
                    unset($params['create_time']);
//                    if($_SESSION['think']['admin']['group_id']==2){
//                        $params['city_id']=$_SESSION['think']['admin']['city_id'];
//                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig("admin",$_SESSION['think']['admin']);
        $this->view->assign("row", $row);
        return $this->view->fetch();

    }

    /**
     * 添加
     */
    public function view($ids = NULL)
    {
        $row=$this->model->getRow($ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function lists($ids = NULL){
        $where="where 1=1";
        if($_SESSION['think']['admin']['group_id']!=1){
            $where.=" and city_id='{$_SESSION['think']['admin']['city_id']}'";
        }
        $page=1;
        $pagesize=50;
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                $keyField = $this->request->request("keyField");
                $keyValue = $this->request->request("keyValue");
                $page = $this->request->request("pageNumber");
                $page = ($page == null) ? 1 : $page;
                $pagesize = $this->request->request("pageSize");
                $pagesize = ($pagesize == null) ? 10 : $pagesize;
                if ($keyValue != "") {
                    $nn=preg_split("/\,/",$keyValue);
                    for($i=0;$i<count($nn);$i++) {
                        $where.= " and $keyField='{$nn[$i]}'";
                    }
                }
            }else{
                $where="where status=1";
                if(isset($_REQUEST['city_id'])&&$_REQUEST['city_id']>0){
                    //$where.=" and city_id=".$_REQUEST['city_id'];
                }
            }
        }
        $sql="select id,week name from dev002_gxyusheng.fa_course_classroomeplan $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
        $list = db()->query($sql);

//        $r_name = model("School")->field("id,name")->where("id", "=", $_REQUEST['school_id'])->select();
//        if (empty($list)&&!empty($r_name)) {
//            $data = array(
//                "type" => "file",
//                "pid" => 0,
//                "name" => $r_name[0]['name']."学科",
//                "title" => $r_name[0]['name'],
//                "ismenu" => 0,
//                "createtime" => time(),
//                "updatetime" => time(),
//                "status" => 1,
//                "school_id" => $_REQUEST['school_id'],
//            );
//            $this->model->create($data);
//        }
//        $sql="select id,pid,name,title,status from dev002_gxyusheng.fa_course_classroomeplan $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
//        $list = db()->query($sql);
//        $tree = Tree::instance();
//        $tree->init($list, 'pid');
//        $list = $tree->getTreeList($tree->getTreeArray(0), 'name');

        $total = db()->query("select count(1) as c from  dev002_gxyusheng.fa_course_classroomeplan $where")[0];
        echo json_encode(array("list" => $list, "total" => $total['c']));
        exit;
    }

    // 导出方法
    public function export()
    {
        $where = $this->buildparams();

        $list = $this->model
            ->where($where)
            ->select();
        $filename = 'classplant_export_' . date('YmdHis');

        $headers = [
            'ID', 'Name', 'Create Time' // 根据实际字段修改
        ];

        $data = [];
        foreach ($list as $item) {
            $data[] = [
                $item['id'],
                $item['name'],
                $item['create_time'],
            ];
        }
        $this->exportExcel($filename, $headers, $data);
    }

    public function status($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result=$this->model->where("id","=",$ids)->field("status")->find();
            $v=$result->status==1?0:1;
            $this->model->where("id","=",$ids)->update(["status"=>$v]);
            $this->success('切换成功!');
        } catch (Exception $e) {
            $this->error('切换失败!'.$e->getMessage());
        }
    }

    public function changeStatus($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result=$this->model->where("id","=",$ids)->field("status")->find();
            $v=$result->status==1?0:1;
            $this->model->where("id","=",$ids)->update(["status"=>$v]);
            $this->success('切换成功!');
        } catch (Exception $e) {
            $this->error('切换失败!'.$e->getMessage());
        }
    }

}
